// 路由配置
import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/stores/user";

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: () => {
      // 根据登录状态和角色智能重定向
      const userStore = useUserStore();
      if (!userStore.isLoggedIn) {
        return "/login";
      }
      return userStore.isPlatformAdmin
        ? "/platform/dashboard"
        : "/tenant/dashboard";
    },
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/auth/Login.vue"),
    meta: { title: "登录", requiresAuth: false },
  },
  // 主应用路由（统一Layout）
  {
    path: "/",
    component: () => import("@/layouts/MainLayout.vue"),
    meta: { requiresAuth: true },
    children: [
      // ========== 平台管理模块 ==========
      {
        path: "platform",
        name: "PlatformModule",
        meta: {
          title: "平台管理",
          icon: "DollarOutlined",
          isModule: true,
          moduleKey: "platform",
          permission: { title: "页面权限", code: "j5m8x1k9" },
          roles: ["PLATFORM_ADMIN"],
          $pageAuthorityRoleTypes: [1], // 只有平台管理员
        },
        children: [
          {
            path: "dashboard",
            name: "PlatformDashboard",
            component: () => import("@/views/platform/dashboard/index.vue"),
            meta: {
              title: "数据概览",
              icon: "DashboardOutlined",
              roles: ["PLATFORM_ADMIN"],
              permission: { title: "页面权限", code: "k9w7x2m4" },
              $pageAuthorityRoleTypes: [1],
            },
          },
          {
            path: "tenant",
            name: "TenantManage",
            component: () => import("@/views/platform/tenant/index.vue"),
            meta: {
              title: "租户管理",
              icon: "TeamOutlined",
              roles: ["PLATFORM_ADMIN"],
              permission: { title: "页面权限", code: "h6v8n3q1" },
              $pageAuthorityRoleTypes: [1],
              $actions: {
                create: {
                  title: "新增",
                  code: "p2z9f5t8",
                  $actionsAuthorityRoleTypes: [1],
                },
                edit: {
                  title: "编辑",
                  code: "r4j6k8m2",
                  $actionsAuthorityRoleTypes: [1],
                },
                delete: {
                  title: "删除",
                  code: "x7c3w9l5",
                  $actionsAuthorityRoleTypes: [1],
                },
              },
            },
          },
          {
            path: "subscription",
            name: "SubscriptionManage",
            component: () => import("@/views/platform/subscription/index.vue"),
            meta: {
              title: "订阅管理",
              icon: "DollarOutlined",
              roles: ["PLATFORM_ADMIN"],
              permission: { title: "页面权限", code: "q8n4v6b1" },
              $pageAuthorityRoleTypes: [1],
              $actions: {
                create: {
                  title: "新增",
                  code: "d5h9j2x7",
                  $actionsAuthorityRoleTypes: [1],
                },
                edit: {
                  title: "编辑",
                  code: "f3k8p6w4",
                  $actionsAuthorityRoleTypes: [1],
                },
                delete: {
                  title: "删除",
                  code: "g7m1z9r5",
                  $actionsAuthorityRoleTypes: [1],
                },
              },
            },
          },
        ],
      },

      // ========== 集货中心模块 ==========
      {
        path: "tenant",
        name: "CollectionModule",
        meta: {
          title: "集货中心",
          icon: "ContainerOutlined",
          isModule: true,
          moduleKey: "collection",
          permission: { title: "页面权限", code: "w7n2p6f8" },
          $pageAuthorityRoleTypes: [1, 11, 21, 31], // 所有租户角色可访问
        },
        children: [
          {
            path: "dashboard",
            name: "TenantDashboard",
            component: () => import("@/views/tenant/dashboard/index.vue"),
            meta: {
              title: "工作台",
              icon: "HomeOutlined",
              hideInMenu: true,
              permission: { title: "页面权限", code: "y5b8n2t6" },
              $pageAuthorityRoleTypes: [1, 11, 21, 31], // 所有角色可访问工作台
            },
          },
          {
            path: "order",
            name: "OrderManage",
            component: () => import("@/views/tenant/order/index.vue"),
            meta: {
              title: "收货开票",
              icon: "FileTextOutlined",
              permission: { title: "页面权限", code: "kpywi5px" },
              // 角色类型：1-平台管理员, 11-租户超管, 21-站点管理员, 31-普通操作员
              $pageAuthorityRoleTypes: [1, 11, 21, 31], // 所有租户角色都可访问
              $actions: {
                create: {
                  title: "新增",
                  code: "w3c7v9k4",
                  $actionsAuthorityRoleTypes: [1, 11, 21, 31], // 所有角色都可新增
                },
                edit: {
                  title: "编辑",
                  code: "l6f2h8m1",
                  $actionsAuthorityRoleTypes: [1, 11, 21, 31],
                },
                delete: {
                  title: "删除",
                  code: "z9x4q7p3",
                  $actionsAuthorityRoleTypes: [1, 11, 21], // 普通操作员不可删除
                },
                assign: {
                  title: "分配",
                  code: "j8n5r2w6",
                  $actionsAuthorityRoleTypes: [1, 11, 21], // 只有管理员可分配
                },
              },
            },
          },
          {
            path: "load",
            name: "LoadManage",
            component: () => import("@/views/tenant/load/index.vue"),
            meta: {
              title: "装车管理",
              icon: "LoadingOutlined",
              permission: { title: "页面权限", code: "e4t7g9l2" },
              $pageAuthorityRoleTypes: [1, 11, 21], // 管理员和站点管理员可操作
              $actions: {
                load: {
                  title: "装车",
                  code: "b6k1m8f5",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
                unload: {
                  title: "卸车",
                  code: "v3h9c7x4",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
              },
            },
          },
          {
            path: "dispatch",
            name: "DispatchManage",
            redirect: "/tenant/dispatch/list",
            meta: {
              title: "发车管理",
              icon: "SendOutlined",
              permission: { title: "页面权限", code: "x2h6w8n4" },
              $pageAuthorityRoleTypes: [1, 11, 21], // 管理员和站点管理员可操作
              $actions: {
                dispatch: {
                  title: "发车",
                  code: "f9k3p7q1",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
                cancel: {
                  title: "撤销发车",
                  code: "v5l2m9c8",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
              },
            },
            children: [
              {
                path: "list",
                name: "DispatchList",
                component: () => import("@/views/tenant/dispatch/index.vue"),
                meta: {
                  title: "发车列表",
                  hideInMenu: true,
                  permission: { title: "页面权限", code: "x2h6w8n4" },
                },
              },
              {
                path: "vehicle/:vehicleId",
                name: "VehicleOrders",
                component: () =>
                  import("@/views/tenant/dispatch/VehicleOrders.vue"),
                meta: {
                  title: "发车订单详情",
                  permission: { title: "页面权限", code: "x2h6w8n4" },
                  hideInMenu: true,
                },
              },
            ],
          },

          {
            path: "order/create",
            name: "OrderCreate",
            component: () => import("@/views/tenant/order/Form.vue"),
            meta: { title: "新建订单", hideInMenu: true },
          },
          {
            path: "order/edit/:id",
            name: "OrderEdit",
            component: () => import("@/views/tenant/order/Form.vue"),
            meta: { title: "编辑订单", hideInMenu: true },
          },
          {
            path: "order/:id",
            name: "OrderDetail",
            component: () => import("@/views/tenant/order/Detail.vue"),
            meta: { title: "订单详情", hideInMenu: true },
          },
          {
            path: "vehicle",
            name: "VehicleManage",
            component: () => import("@/views/tenant/vehicle/index.vue"),
            meta: {
              title: "车辆管理",
              icon: "CarOutlined",
              permission: { title: "页面权限", code: "s8j4p1w9" },
              $pageAuthorityRoleTypes: [1, 11], // 只有租户超管可管理车辆（公司级资源）
              $actions: {
                create: {
                  title: "新增",
                  code: "a7z2q6n8",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                edit: {
                  title: "编辑",
                  code: "m5k9r3f7",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                delete: {
                  title: "删除",
                  code: "t4x8c1l6",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
              },
            },
          },
          {
            path: "vehicle/create",
            name: "VehicleCreate",
            component: () => import("@/views/tenant/vehicle/Form.vue"),
            meta: { title: "新增车辆", hideInMenu: true },
          },
          {
            path: "vehicle/edit/:id",
            name: "VehicleEdit",
            component: () => import("@/views/tenant/vehicle/Form.vue"),
            meta: { title: "编辑车辆", hideInMenu: true },
          },
          {
            path: "vehicle/:id",
            name: "VehicleDetail",
            component: () => import("@/views/tenant/vehicle/Detail.vue"),
            meta: { title: "车辆详情", hideInMenu: true },
          },
          {
            path: "driver",
            name: "DriverManage",
            component: () => import("@/views/tenant/driver/index.vue"),
            meta: {
              title: "司机管理",
              icon: "TeamOutlined",
              permission: { title: "页面权限", code: "i9w7b3h2" },
              $pageAuthorityRoleTypes: [1, 11, 21], // 租户超管和站点管理员可管理司机
              $actions: {
                create: {
                  title: "新增",
                  code: "u8g5p4j1",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
                edit: {
                  title: "编辑",
                  code: "o6v9k2x7",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
                delete: {
                  title: "删除",
                  code: "n3f8z5w4",
                  $actionsAuthorityRoleTypes: [1, 11, 21],
                },
              },
            },
          },
          {
            path: "driver/create",
            name: "DriverCreate",
            component: () => import("@/views/tenant/driver/Form.vue"),
            meta: { title: "新增司机", hideInMenu: true },
          },
          {
            path: "driver/edit/:id",
            name: "DriverEdit",
            component: () => import("@/views/tenant/driver/Form.vue"),
            meta: { title: "编辑司机", hideInMenu: true },
          },
          {
            path: "driver/:id",
            name: "DriverDetail",
            component: () => import("@/views/tenant/driver/Detail.vue"),
            meta: { title: "司机详情", hideInMenu: true },
          },
        ],
      },

      // ========== 到货中心模块 ==========
      {
        path: "tenant/arrival",
        name: "ArrivalModule",
        meta: {
          title: "到货中心",
          icon: "DeliveredProcedureOutlined",
          isModule: true,
          moduleKey: "arrival",
          permission: { title: "页面权限", code: "q3v7t9b5" },
          $pageAuthorityRoleTypes: [1, 11, 21, 31], // 所有角色可查看
        },
        children: [
          // 到货管理
          {
            path: "list",
            name: "ArrivalList",
            component: () => import("@/views/tenant/arrival/index.vue"),
            meta: {
              title: "到货管理",
              icon: "InboxOutlined",
              permission: { title: "页面权限", code: "c7m1q9r6" },
              $pageAuthorityRoleTypes: [1, 11, 21, 31],
            },
            children: [
              {
                path: ":id",
                name: "ArrivalDetail",
                component: () => import("@/views/tenant/arrival/Detail.vue"),
                meta: {
                  title: "到货详情",
                  hideInMenu: true,
                  permission: { title: "页面权限", code: "c7m1q9r6" },
                  $pageAuthorityRoleTypes: [1, 11, 21, 31],
                },
              },
            ],
          },
          // 车辆到站
          {
            path: "vehicle-arrival",
            name: "VehicleArrival",
            component: () =>
              import("@/views/tenant/arrival/VehicleArrival.vue"),
            meta: {
              title: "车辆到站",
              icon: "CarOutlined",
              permission: { title: "页面权限", code: "v8a2s4d1" },
              $pageAuthorityRoleTypes: [1, 11, 21, 31],
            },
            children: [
              {
                path: "vehicle/:vehicleId",
                name: "ArrivalVehicleOrders",
                component: () =>
                  import("@/views/tenant/arrival/VehicleOrders.vue"),
                meta: {
                  title: "车辆订单详情",
                  hideInMenu: true,
                  permission: { title: "页面权限", code: "v8a2s4d1" },
                  $pageAuthorityRoleTypes: [1, 11, 21, 31],
                },
              },
            ],
          },
        ],
      },

      // ========== 财务中心模块 ==========
      {
        path: "tenant/finance",
        name: "FinanceModule",
        meta: {
          title: "财务中心",
          icon: "AccountBookOutlined",
          isModule: true,
          moduleKey: "finance",
          permission: { title: "页面权限", code: "c4h9k2m7" },
          $pageAuthorityRoleTypes: [1, 11], // 只有超级管理员可查看财务
        },
        children: [
          // TODO: 待开发
        ],
      },

      // ========== 数据中心模块 ==========
      {
        path: "tenant/data",
        name: "DataModule",
        meta: {
          title: "数据中心",
          icon: "PieChartOutlined",
          isModule: true,
          moduleKey: "data",
          permission: { title: "页面权限", code: "z8f3x6w1" },
          $pageAuthorityRoleTypes: [1, 11, 21], // 管理员可查看数据
        },
        children: [
          // TODO: 待开发
        ],
      },

      // ========== 系统设置模块 ==========
      {
        path: "tenant/settings",
        name: "SettingsModule",
        meta: {
          title: "系统设置",
          icon: "SettingOutlined",
          isModule: true,
          moduleKey: "settings",
          permission: { title: "页面权限", code: "g6l4r9h2" },
        },
        children: [
          {
            path: "dictionary",
            name: "DictionaryManage",
            component: () => import("@/views/tenant/settings/Dictionary.vue"),
            meta: {
              title: "字典管理",
              icon: "BookOutlined",
              permission: { title: "页面权限", code: "d8l4h7p2" },
              $pageAuthorityRoleTypes: [1, 11], // 只有超级管理员可管理字典
              $actions: {
                create: {
                  title: "新增",
                  code: "f2j6v9k3",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                edit: {
                  title: "编辑",
                  code: "g5x8n1w7",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                delete: {
                  title: "删除",
                  code: "h9c4z6m2",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
              },
            },
          },
          {
            path: "role",
            name: "RoleManagement",
            component: () =>
              import("@/views/tenant/settings/RoleManagement.vue"),
            meta: {
              title: "角色权限",
              icon: "SafetyOutlined",
              permission: { title: "页面权限", code: "r3t8q5l9" },
              $pageAuthorityRoleTypes: [1, 11], // 只有租户超管可管理角色
              $actions: {
                create: {
                  title: "新增",
                  code: "k7w2f6b4",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                edit: {
                  title: "编辑",
                  code: "p1m9x5v8",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                delete: {
                  title: "删除",
                  code: "q6j3h7c1",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                assign: {
                  title: "分配权限",
                  code: "y4n8g2z9",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
              },
            },
          },
          {
            path: "user",
            name: "UserManagement",
            component: () =>
              import("@/views/tenant/settings/UserManagement.vue"),
            meta: {
              title: "用户管理",
              icon: "UserOutlined",
              permission: { title: "页面权限", code: "l5k9w7x3" },
              $pageAuthorityRoleTypes: [1, 11], // 只有超级管理员可管理用户
              $actions: {
                create: {
                  title: "新增",
                  code: "b8f1p6j4",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                edit: {
                  title: "编辑",
                  code: "v2h7m9c5",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                delete: {
                  title: "删除",
                  code: "z6t4q8r1",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
                resetPassword: {
                  title: "重置密码",
                  code: "x3w9l2k7",
                  $actionsAuthorityRoleTypes: [1, 11],
                },
              },
            },
          },
        ],
      },

      // ========== 通用页面 ==========
      {
        path: "profile",
        name: "Profile",
        component: () => import("@/views/tenant/profile/index.vue"),
        meta: { title: "账户信息", hideInMenu: true },
      },
    ],
  },
  // 旧路由重定向（兼容性）
  {
    path: "/platform",
    redirect: "/platform/dashboard",
  },
  {
    path: "/tenant",
    redirect: "/tenant/dashboard",
  },
  {
    path: "/no-permission",
    name: "NoPermission",
    component: () => import("@/views/common/NoPermission.vue"),
    meta: { title: "无权限", requiresAuth: true },
  },
  // 404 页面
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/common/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, _from, next) => {
  const userStore = useUserStore();

  // 设置页面标题
  document.title = `${to.meta.title || ""} - 物流配送管理系统`;

  // 如果访问登录页，直接放行
  if (to.path === "/login") {
    next();
    return;
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next("/login");
    return;
  }

  // 检查角色权限
  if (to.meta.roles && userStore.userInfo) {
    const roles = to.meta.roles as string[];
    if (!roles.includes(userStore.userInfo.role)) {
      // 没有权限，跳转到对应首页
      if (userStore.isPlatformAdmin) {
        next("/platform/dashboard");
      } else {
        next("/tenant/dashboard");
      }
      return;
    }
  }

  /**
   * 模块级访问放行逻辑
   * 当目标路由为模块路由（meta.isModule === true）时：
   * 1) 收集其所有可见子路由的菜单权限码（含多级子路由）
   * 2) 只要用户拥有任一子页面权限，即允许进入该模块
   * 3) 若用户不具备任一子页面权限，则再按模块自身的权限码校验，失败跳转无权限页
   */
  if ((to.meta as any)?.isModule) {
    const routes = router.getRoutes();

    /**
     * 收集目标模块路由的所有子页面权限码（深度遍历）
     */
    const collectChildPerms = (routeName: string): string[] => {
      const target = routes.find((r) => r.name === routeName);
      const result: string[] = [];

      const walk = (record: any) => {
        if (!record) return;
        const m = record.meta as any;
        if (m?.permission) {
          // 支持新的对象格式 { title, code } 和旧的字符串格式
          const permCode =
            typeof m.permission === "string" ? m.permission : m.permission.code;
          if (permCode) result.push(permCode);
        }
        if (record.children && record.children.length > 0) {
          record.children.forEach((c: any) => walk(c));
        }
      };

      if (target?.children && target.children.length > 0) {
        target.children.forEach((c) => walk(c));
      }
      return result;
    };

    const childPerms = collectChildPerms(to.name as string);
    if (childPerms.length > 0 && userStore.hasAnyPermission(childPerms)) {
      next();
      return;
    }

    const modulePerm = (to.meta as any).permission;
    if (modulePerm) {
      const permCode =
        typeof modulePerm === "string" ? modulePerm : modulePerm.code;
      if (permCode && !userStore.hasPermission(permCode)) {
        next("/no-permission");
        return;
      }
    }
  }

  // 路由权限点校验（非模块路由必须要有页面权限才能访问）
  if (to.meta.permission && !(to.meta as any)?.isModule) {
    const perm = (to.meta as any).permission;
    // 支持新的对象格式 { title, code } 和旧的字符串格式
    const permCode = typeof perm === "string" ? perm : perm.code;
    if (!permCode) {
      if (to.name === "TenantDashboard") {
        next();
        return;
      }
      next("/no-permission");
      return;
    }
    // 检查页面权限（hasPermission 已支持原始权限码和 page_ 前缀格式）
    if (!userStore.hasPermission(permCode)) {
      // 必须要有页面权限才能访问
      if (to.name === "TenantDashboard") {
        next();
        return;
      }
      next("/no-permission");
      return;
    }
  }

  next();
});

export default router;
